<template>
  <div>
    <div ref="progressBar" style="width: 100%; height: 300px" />
  </div>
</template>

<script>
import * as echarts from 'echarts'
import resize from '@/mixins/resize'

export default {
  name: 'PieChart',
  components: {},
  mixins: [resize],
  props: {
    chartData: {
      type: Array,
      default: () => []
    },
    percentage: {
      type: Number,
      default: 0
    }
  },
  data() {
    return { chart: null }
  },

  computed: {},
  watch: {
    chartData: {
      deep: true,
      handler(val) {
        this.setOptions(val) // 监听数据变化
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose() // 销毁echart
    this.chart = null
  },
  methods: {

    resize() {
      this.$nextTick(() => {
        this.chart.resize()
      })
      console.log('resize')
    },
    // 初始化图表
    initChart() {
      this.chart = echarts.init(this.$refs.progressBar)
      this.setOptions()
    },
    // 图表配置项
    setOptions() {
      const color = this.percentage === 100 ? '#53C291' : '#6A73FD'
      this.chart.setOption({
        color: [color, '#eeeeee'],
        series: [
          {
            name: 'xx',
            type: 'pie',
            radius: ['50%', '70%'], // 决定圆环的位置及粗细
            avoidLabelOverlap: false, // 是否启用防止标签重叠策略
            hoverAnimation: false, // 关闭放大动画
            selectedOffset: 0, // 选中块的偏移量
            label: {
              show: false,
              position: 'center',
              formatter: '{d}%'
            },
            labelLine: {
              show: false
            },
            data: [
              { // 进度条数据data
                value: this.percentage,
                name: 'xx',
                selected: true, // 默认选中第一块
                itemStyle: { // 设置相同的默认颜色和高亮颜色
                  normal: { color },
                  emphasis: { color }
                },
                label: {
                  show: true, // 默认显示第一块
                  fontSize: '24',
                  color,
                  fontWeight: 'bold'
                }
              },
              { // 灰色块data
                value: 100 - this.percentage,
                name: 'xx',
                itemStyle: { // 设置相同的默认颜色和高亮颜色
                  normal: { color: '#eeeeee' },
                  emphasis: { color: '#eeeeee' }
                }
              }
            ]
            // itemStyle: {
            //   borderWidth: 5, // 设置的是每项之间的留白
            //   borderColor: '#fff'
            // }
          }
        ]
      })
    }
  }
}
</script>
